if (typeof jQuery === 'undefined') {
    throw new Error('jquery.button JavaScript requires jQuery');
}

if (typeof Plugin === 'undefined') {
    throw new Error('jquery.button JavaScript requires Plugin');
}


(function () {
    'use strict';

    var Button = function (el, options) {
        this.$el = $(el);
        this.namespace = _config_.button.namespace;
        this.defaults = _config_.button.defaults;
        this.methods = _config_.button.methods;
        this.events = _config_.button.events;

        if (this.$el.prop('tagName') === 'BUTTON') {
            this.defaults.type = this.$el.prop('type').toUpperCase();
        } else {
            this.defaults.type = this.$el.prop('tagName').toUpperCase();
        }

        if (this.defaults.type === 'SUBMIT') {
            this.defaults.type = 'POST';
        }

        if (this.$el.prop('tagName') === 'BUTTON' && this.$el.prop('type').toUpperCase() === 'SUBMIT') {
            this.$el.attr('type', 'submit');
        } else {
            this.$el.attr('type', 'button');
        }

        this.getForm();
        //field 初始值合并form元素值, 默认值, 和field元素值
        this.initials = $.com.getDataBindFromElement(this.$el);
        var button = _config_.button.actions[this.initials.button] || _config_.button.actions.default;
        this.initials = $.extend(true, {}, _config_.button.initials, button, this.initials);
        this.originals = $.extend(true, {}, this.defaults, this.initials);
        this.originals.type = this.originals.type.toUpperCase();
        this.originals.side = this.originals.side.toLowerCase();
        this.originals.label = this.$el.text() || this.originals.label;
        this.originals.enterPress = this.originals.enterPress || false;
        this.$el.attr('data-enter-press', this.originals.enterPress);
        this.$el.attr('data-close-on-success', this.originals.closeOnSuccess);
        this.options = $.extend(true, {}, this.originals, options);
        this.options.serial = $.com.getSerial(16);
        //父级弹出框
        this.$popup = this.$el.closest(_config_.selector.popupWindow);
        //处理id
        this.getNamedPrefix('name');
        this.$template = $(this.options.template).children();
        this.button = this.options.button;
        this.init();
        this.options.el = this;
    };

    Button.prototype = new Plugin();

    Button.prototype.init = function () {
        this.initButton();
        this.initEvent();
    };

    Button.prototype.initButton = function () {
        if (!$.com.hasValue(this.options.url) && $.com.isJqueryObject(this.$form)) {
            var form = this.$form.data(_config_.form.namespace);
            if ($.com.hasValue(form)) {
                this.options.url = form.options.url;
                this.initials.url = this.options.url;
            }
        }

        this.execute(this.options.loading);

        if (this.options.authorize) {
            this.onAuthorization();
        }

        if (this.options.button !== _config_.button.actions.default.name) {
            if (this.options.withGroup) {
                var that = this;
                if ($.com.hasValue(this.options.url) && this.options.side === 'server') {
                    //download or export list from server
                    var downloadListClass = $('#__TemplateDownloadList').children().attr('class');
                    this.$el.addClass(downloadListClass);
                    this.$el.empty();
                    $.api.get(this.options.url, function (d) {
                        if ($.isFunction(that.options.dataAdapter)) {
                            d = that.options.dataAdapter(d, this.options.dataValueField, this.options.dataTextField);
                        }

                        if ($.com.isArray(d)) {
                            for (var i = 0; i < d.length; i++) {
                                var btn = '<button type="button" ' + _config_.attribute.button + '="download" data-url="' + d[i].Path + '">' + d[i].Name + '</button>';
                                var $button = $(btn);
                                $button.addClass('btn btn-sm waves-effect waves-light btn-default');
                                that.$el.append($button);
                            }

                            that.$el.children().button();
                        }
                    });
                } else {
                    //download or export list from client
                    var $template = $('#__TemplateButtonGroup').children().clone();
                    this.$el.addClass($template.attr('class'));
                    var $button = $template.children('button');
                    $button.addClass(this.options.class);
                    $button.html(this.$template.clone());
                    $button.children('.button-label').html(this.options.label);
                    $button.children('.caret').css('display', 'inline-block');
                    if ($.com.hasValue(this.options.icon)) {
                        $button.children('.button-icon').addClass(this.options.icon);
                    }

                    var $content = $template.children('ul.dropdown-menu').empty();
                    this.$el.append($template.children());
                    this.$el.children().not($content).not($button).each(function () {
                        var $this = $(this);
                        var $li = $('<li></li>');
                        $content.append($li);
                        if ($this.is('.divider')) {
                            $li.addClass('divider');
                        } else {
                            $li.append($this);
                            $this.attr('data-button', that.options.button);
                            $this.button();
                        }
                    });
                }
            } else if (!$.com.isJqueryObject(this.$el.parents('[data-with-group="true"]'))) {
                if ($.com.isJqueryObject(this.$template)) {
                    this.$el.html(this.$template.clone());
                    if ($.com.hasValue(this.options.class)) {
                        this.$el.addClass('btn btn-sm waves-effect waves-light');
                        this.$el.addClass(this.options.class);
                        //title = "编辑" aria- label="编辑"
                        if ($.com.hasValue(this.options.title)) {
                            this.$el.attr({ 'title': this.options.title, 'aria-label': this.options.title });
                        }
                    }

                    if ($.com.hasValue(this.options.label)) {
                        this.$el.find('span.button-label').html(this.options.label);
                    } else {
                        this.$el.find('span.button-label').remove();
                        this.$el.css('box-shadow', 'inherit');
                    }

                    this.$el.find('.caret').remove();
                    if ($.com.hasValue(this.options.icon)) {
                        this.$el.find('span.button-icon').addClass(this.options.icon);
                    } else {
                        this.$el.find('span.button-icon').remove();
                    }
                }

                if (this.options.button === 'import') {
                    this.$el.find('input.button-input').attr('data-button', this.options.button).attr('data-field', this.options.id).attr('data-label', this.options.label).field();
                    this.$el.find('input.k-widget.k-upload').hide();
                } else if (this.options.button === 'upload') {
                    this.$el.addClass('fileupload');
                    this.$fileupload = this.$el.find('form.upload-form');
                    if ($.com.isJqueryObject(this.$fileupload)) {
                        this.options.url = this.options.url || _config_.default.attachmentUpload;
                        this.$fileupload.attr('action', this.options.url);

                        let $upload = this.$el.find('input.button-input').addClass('upload');
                        if ($.com.hasValue(this.options.fileExtension)) {
                            $upload.attr('accept', this.options.fileExtension);
                        }

                        if (this.options.multiple || $.com.hasValue(this.options.fileCount) && this.options.fileCount > 1) {
                            $upload.attr('multiple', true);
                        }

                        this.$fileupload.fileupload({
                            singleFileUploads: false,
                            limitMultiFileUploads: this.options.fileCount,
                            limitMultiFileUploadSize: this.options.fileCount * this.options.fileSize,
                            send: (event, data) => this.onUpload(event, data),
                            done: (event, data) => this.options.success && this.options.success(event, data, data.result),
                            fail: (event, data) => this.options.error && this.options.error(event, data, data.result),
                            always: (event, data) => this.options.complete && this.options.complete(event, data, data.result)
                        });
                    }
                }
            }
        }

        this.$el.attr(_config_.attribute.initial, true);
        this.execute(this.options.loaded);
    };

    Button.prototype.initEvent = function () {
        if (!this.options.withGroup) {
            var that = this;
            this.$el.off('click.' + this.namespace).on('click.' + this.namespace, event => {
                this.onClick(event);
                event.stopPropagation();
            });

            if (this.options.button === 'upload') {
                this.$el.off('change.' + this.namespace, ':file').on('change.' + this.namespace, ':file', event => this.onChange(event));
            }

            if (this.options.button === 'advancedSearch') {
                var $target = $(this.options.target);
                if ($.com.hasValue($target)) {

                    $(document).find('.body-content').off('click.' + this.namespace).on('click.' + this.namespace, event => {
                        $target.slideUp({ speed: 'slow' });
                        $.com.advancedSearchColorful(that.$el);
                        //折叠后执行查询在保存了查询条件情况下不好用
                        //that.onQuery();
                    });

                    $target.off('click.' + this.namespace).on('click.' + this.namespace, event => {
                        if (!$target.is(':hidden')) {
                            event.stopPropagation();
                        }
                    });

                    $target.attr('tabindex', 0).off('keypress.' + this.namespace).on('keypress.' + this.namespace, event => {
                        if (event.key === 'Enter') {
                            $target.slideUp({ speed: 'slow' });
                            $.com.advancedSearchColorful(that.$el);
                            this.onQuery();
                        }
                    });
                }
            }
        }
    };

    Button.prototype.display = function (arg) {
        arg = $.com.hasValue(arg) ? arg : this.initials.display;
        this.options.display = !!($.com.hasValue(arg) ? arg : this.options.display);
        if ($.com.hasValue(arg)) {
            if (this.options.display) {
                this.$el.show();
            } else {
                this.$el.hide();
            }

            return;
        }

        if ($.com.isJqueryObject(this.$form)) {
            var form = this.$form.data(_config_.form.namespace);
            if ($.com.hasValue(form)) {
                var formData = form.options.data;
                var isAuditing = $.com.hasValue(this.options.isAuditing) && this.options.isAuditing;
                if ($.com.hasValue(this.options.displayInEditable)) {
                    //1. 编辑页面按钮显示
                    //1.1. 根据配置 displayInEditable 决定是否显示
                    //此时情况这两种情况显示:a.编辑页面且配置为编辑页面显示;b.非编辑页面且配置为编辑页面不显示
                    if ((form.options.editable && this.options.displayInEditable) || (!form.options.editable && !this.options.displayInEditable)) {
                        this.$el.show();
                    } else {
                        this.$el.hide();
                    }

                    //1.2. 根据 业务数据是否有审核流程 决定是否显示
                    if (isAuditing) {
                        if (form.options.editable) {
                            if ($.com.hasValue(formData)) {
                                //2.1.更新按钮,提交备案按钮:业务数据是草稿状态的时候 显示
                                //2.2.保存按钮,提交变更按钮:业务数据是Available 或者 Updated 状态的时候 显示
                                if (this.options.button == "put" || this.options.button == "register") {
                                    if (formData.state == _config_.default.dataState.draft.toUpperCase()) {
                                        this.$el.show();
                                    } else {
                                        this.$el.hide();
                                    }
                                } else if (this.options.button == "save" || this.options.button == "submitChange") {
                                    if (formData.state == _config_.default.dataState.available.toUpperCase() || formData.state == _config_.default.dataState.updated.toUpperCase()) {
                                        this.$el.show();
                                    } else {
                                        this.$el.hide();
                                    }
                                }
                            }
                        } else {
                            //配置为编辑页面显示,但新增页面也显示
                            if (this.options.button == "register") {
                                this.$el.show();
                            }
                        }
                    }
                } else {
                    //2. 详情页面按钮显示
                    if (isAuditing && $.com.hasValue(formData)) {
                        var hasAudit = $.com.hasValue(formData.auditRecordId) && $.com.hasValue(formData.auditRecord);
                        var isRejected = hasAudit && formData.auditRecord.auditState == _config_.default.auditState.rejected;
                        var isPending = hasAudit && formData.auditRecord.auditState == _config_.default.auditState.pending;
                        if (this.options.button == "edit") {
                            if (isPending) {
                                this.$el.hide();
                            } else {
                                this.$el.show();
                            }
                        } else if (this.options.button == "delete") {
                            if (formData.state == _config_.default.dataState.draft && (!$.com.hasValue(formData.auditRecordId) || isRejected)) {
                                this.$el.show();
                            } else {
                                this.$el.hide();
                            }
                        } else if (this.options.button == "abort") {
                            if (isRejected) {
                                this.$el.show();
                            } else {
                                this.$el.hide();
                            }
                        } else if (this.options.button == "cancel") {
                            if (isRejected || isPending) {
                                this.$el.show();
                            } else {
                                this.$el.hide();
                            }
                        }
                    }
                }

                var isDataValid = formData.state == _config_.default.dataState.canceled;
                if (isDataValid && this.options.button != "close") {
                    this.$el.hide();
                }
            }
        };
    }

    Button.prototype.destroy = function () {
        var formData = this.$form.data(_config_.form.namespace);
        if ($.com.hasValue(formData) && formData.$buttons.hasValue()) {
            formData.$buttons.removeItem(this.$el);
        }

        this.$el.removeData(_config_.button.namespace);
        this.$el.remove();
    };

    Button.prototype.onClick = function (event) {
        var args = {};
        this.getForm();

        //现在前置事件只需返回 false 就可以阻止事件继续执行
        var ret = this.execute(this.options.clicking, event, args);
        if ($.com.hasValue(ret) && ret === false) {
            return;
        }

        if ($.com.hasValue(this.options.button) && $.com.hasValue(this.options.action)) {
            let fun = (typeof this.options.action === 'function') ? this.options.action : () => {
                var actions = this.options.action.replace(/\,\ ?/, ',').split(',');
                if ($.com.isArray(actions)) {
                    var that = this;
                    for (var i = 0; i < actions.length; i++) {
                        var action = that[actions[i]];
                        if (!$.isFunction(action)) {
                            action = $.com.getFunction(actions[i]);
                        }

                        if ($.isFunction(action)) {
                            action.apply(that, [event, args]);
                        }
                    }
                }
            };

            if (this.options.confirm) {
                app.question(this.options.confirmText).then(res => {
                    if (res) {
                        fun();
                    }
                });
            } else {
                fun();
            }
        }

        this.execute(this.options.clicked, event, args);
    };

    Button.prototype.onChange = function (event) {
        //现在前置事件只需返回 false 就可以阻止事件继续执行
        var ret = this.execute(this.options.changeing, event);
        if ($.com.hasValue(ret) && ret === false) {
            return;
        }

        if (this.options.button === 'upload' && (!this.onUpload(event))) {
            return;
        }

        this.execute(this.options.changed, event);
    };

    Button.prototype.onLink = function () {
        if ($.com.hasValue(this.options.url)) {
            var linkUrl = this.options.url;
            if ($.com.isArray(this.options.data)) {
                linkUrl += '?' + this.options.textField + '=' + this.options.data[0][this.options.valueField];
            }

            location.href = linkUrl;
        }
    };

    Button.prototype.onClear = function () {
        if ($.com.isJqueryObject(this.$form)) {
            var form = this.$form.data(_config_.form.namespace);
            form.clear();
        }
    };

    Button.prototype.onReset = function () {
        if ($.com.isJqueryObject(this.$form)) {
            var form = this.$form.data(_config_.form.namespace);
            form.reset();
        }
    };

    Button.prototype.onAddForm = function (event, args) {
        if ($.com.isJqueryObject(this.$form)) {
            this.$form.form('addForm', args);
        }
    };

    Button.prototype.onRemoveForm = function (event, args) {
        if ($.com.isJqueryObject(this.$form)) {
            this.$form.form('removeForm', args);
        }
    };

    Button.prototype.onQuery = function () {
        if ($.com.isJqueryObject(this.$form)) {
            var form = this.$form.data(_config_.form.namespace);
            if ($.com.hasValue(form)) {
                if (!$.com.isJqueryObject(this.$grid)) {
                    this.$grid = $(this.options.grid || _config_.selector.default);
                    if (!this.$grid.hasValue()) {
                        this.$grid = form.$grid;
                        if (!this.$grid.hasValue()) {
                            this.$grid = $(form.options.grid);
                        }
                    }
                }

                if (this.$grid.hasValue()) {
                    var grid = this.$grid.data(_config_.grid.namespace);
                    if ($.com.hasValue(grid)) {
                        //form.getQueryExpression();
                        //var dataSource = $.com.getDataSource(grid.role);
                        //dataSource = $.com.getQueryOptions(dataSource, form.options.dataSource);
                        //if ($.com.hasValue(dataSource)) {
                        //    dataSource.page = 1;
                        //    dataSource.autoQuery = true;
                        //    grid.role.dataSource.query(dataSource);
                        //    grid.resize();
                        //    grid.initEvent();
                        //}
                        grid.query();
                    }
                }

                var $advancedSearch = form.$buttons.filter('[data-button="advancedSearch"]').first();
                if ($.com.isJqueryObject($advancedSearch)) {
                    if (this.options.autoShrink) {
                        var $target = $($advancedSearch.attr('data-target'));
                        if ($.com.hasValue($target)) {
                            $target.slideUp({ speed: 'slow' });
                        }
                    }

                    $.com.advancedSearchColorful($advancedSearch);
                }
            }
        }
    };

    Button.prototype.onAdvancedSearch = function (event) {
        var $target = $(this.options.target);
        if ($.com.hasValue($target)) {
            $target.slideToggle({ speed: 'slow' });
            $target.addClass('col-md-12');
            $.com.resizeAdvancedSearch(this.$el);
        }

        event.stopPropagation();
    };

    Button.prototype.onApprove = function () {
        let $businessForm = this.$form;
        let $auditForm = this.$form.find('[data-toggle="form"][data-field="AuditRecord"]');
        this.$form = $auditForm;
        let form = $businessForm.data(_config_.form.namespace);
        if ($.com.hasValue(form)) {
            let id = form.getValue('options.data.Id');
            if ($.com.hasValue(id)) {
                this.$form.find('[data-field="BusinessKey"]').val(id).change();
            }
        }

        //var $input = this.$form.find('[data-toggle="form"][data-field="ApprovingSuggestion"]');
        //if ($.com.isJqueryObject($input)) {
        //    $input.val('approved').change();
        //}
    };

    Button.prototype.onReject = function () {
        let $businessForm = this.$form;
        let $auditForm = this.$form.find('[data-toggle="form"][data-field="AuditRecord"]');
        this.$form = $auditForm;
        let form = $businessForm.data(_config_.form.namespace);
        if ($.com.hasValue(form)) {
            let id = form.getValue('options.data.Id');
            if ($.com.hasValue(id)) {
                this.$form.find('[data-field="BusinessKey"]').val(id).change();
            }
        }

        //var $input = this.$form.find('[data-toggle="form"][data-field="ApprovingSuggestion"]');
        //if ($.com.isJqueryObject($input)) {
        //    $input.val('approved').change();
        //}
    };

    Button.prototype.onUpload = function (event, data) {
        //移除超出文件
        let files = data.files || event.target.files;
        if ($.com.hasValue(this.options.fileCount) && (files.length > this.options.fileCount)) {
            app.warning('只能上传 ' + this.options.fileCount + ' 个文件!');
            event.stopPropagation();
            return false;
        }

        if (files.length > 0) {
            if (this.options.fileExtension !== '*') {
                var exts = this.options.fileExtension + ',';
                for (var index = 0; index < files.length; index++) {
                    let file = files[index];

                    //验证文件类型
                    if (!exts.includes($.com.getFileExtension(file.name).toLowerCase() + ',')) {
                        app.warning('只能上传 ' + this.options.fileExtension + ' 类型的文件!');
                        event.stopPropagation();
                        return false;
                    }

                    //验证文件大小
                    if (file.size > this.options.fileSize * 1024) {
                        var size = this.options.fileSize;
                        if ((size / 1024) >= 1) {
                            size = $.com.toFixed(size / 1024, 2) + 'MB';
                        } else {
                            size = size + 'KB';
                        }

                        app.warning('单个文件不能超过 ' + size + ' 大小!');
                        event.stopPropagation();
                        return false;
                    }
                }
            }
        }

        return true;
    };

    Button.prototype.onDownload = function () {
        app.download(this.options.filePath || this.options.url, this.options.fileName);
    };

    Button.prototype.onImport = function (event) {
        if ($.com.hasValue(this.options.fileName) && $.com.hasValue(this.originals.url)) {
            this.options.url = this.originals.url + (this.originals.url.includes('?') ? '&' : '?') + 'fileName=' + this.options.fileName;
            $.api.post(this.options);
        } else {
            var $input = this.$el.find('input:file[id]');
            if ($input.hasValue() && !$input.equal(event.target)) {
                $input.click();
            }
        }
    };

    Button.prototype.onExport = function () {
        if (!$.com.hasValue(this.options.url)) {
            return;
        }

        this.$grid = $(this.options.grid || _config_.selector.default);
        if (!$.com.isJqueryObject(this.$grid) && $.com.isJqueryObject(this.$form)) {
            var form = this.$form.data(_config_.form.namespace);
            if ($.com.hasValue(form)) {
                this.$grid = form.$grid;
                if (!this.$grid.hasValue()) {
                    this.$grid = $(form.options.grid);
                }
            }
        }

        var queryString = $.com.getQueryString(this.options.url);
        var url = queryString.url;
        if (this.$grid.hasValue()) {
            var grid = this.$grid.data(_config_.grid.namespace);
            if ($.com.hasValue(grid)) {
                var dataSource = $.com.getDataSource(grid.role);
                if ($.com.hasValue(form.options.dataSource)) {
                    dataSource = $.com.getQueryOptions(dataSource, form.options.dataSource);
                }

                if ($.com.hasValue(dataSource)) {
                    if (!$.com.isArray($.com.getValue(dataSource, 'filter.filters'))) {
                        if ($.com.isNullOrEmpty(dataSource.filter)) {
                            dataSource.filter = { filters: [] };
                        } else {
                            dataSource.filter = { filters: [dataSource.filter] };
                        }
                    }

                    //导出的时候不分页
                    //if ($.com.hasValue(dataSource.pageSize) && $.com.hasValue(dataSource.page)) {
                    //    queryString.$top = dataSource.pageSize;
                    //    queryString.$skip = (dataSource.page - 1) * dataSource.pageSize;
                    //}

                    var transportDataSource = grid.role.dataSource.transport.parameterMap(dataSource, 'read') || {};
                    var transportData = $.com.getValue(dataSource, 'transport.read.data') || {};
                    queryString = $.extend(queryString, transportDataSource, transportData);
                    var gridUrl = $.com.getValue(grid, 'role.options.dataSource.transport.read.url');
                    if ($.com.hasValue(gridUrl)) {
                        queryString = $.extend(queryString, $.com.getQueryString(gridUrl));
                    }
                }
            }
        }

        delete queryString.url;
        delete queryString.group;
        url += $.com.getQueryString(queryString);
        app.download(url, this.options.fileName);
    };

    Button.prototype.onSubmit = function () {
        this.options.type = (this.options.type || 'POST').toUpperCase();
        if (this.options.withFormData && $.com.isJqueryObject(this.$form)) {
            var form = this.$form.data(_config_.form.namespace);
            form.writeBack();
            if (!$.com.isNullOrEmpty(form)) {
                const id = form.options.data[form.options.dataIdField];
                if ($.com.hasValue(this.options.keepReference) && !this.options.keepReference && $.com.hasValue(this.options.url) && $.com.hasValue(id)) {
                    let arg = id;
                    if (this.options.url.includes('odata')) {
                        arg = (form.options.dataIdType === 'string') ? `('${id}')` : `(${id})`;
                    } else {
                        arg = `/${id}`;
                    }

                    this.options.url = this.initials.url + arg;
                    this.options.data = {};
                } else {
                    if (this.options.type !== 'DELETE' && form.validate(this.options.validator) === false) {
                        app.warning('字段校验尚未通过!');
                        return;
                    }

                    let ignoreFields = form.options.ignoreFields;
                    ignoreFields = $.com.hasValue(ignoreFields) ? (ignoreFields + ',' + _config_.default.ignoreFields) : _config_.default.ignoreFields;
                    this.options.data = $.com.cleanData(form.options.data, ignoreFields);
                }
            }
        }

        if ($.com.hasValue(this.options.url)) {
            //现在前置事件只需返回 false 就可以阻止事件继续执行
            var ret = this.execute(this.options.beforeSubmit);
            if ($.com.hasValue(ret) && ret === false) {
                return;
            }

            $.api.ajax(this.options);
        }
    };

    Button.prototype.onAuthorization = function () {
        if ($.com.hasValue(this.options.functionid) || $.isFunction(this.options.authorizeMethod)) {
            var that = this;

            var serverAuthorize = function (functionid) {
                $.api.get('/api/Common/AuthorizationFunction/' + functionid, function (d) {
                    that.execute(that.options.authorizeComplete, d);
                    if (d) {
                        that.options.isAuthenticated = true;
                        that.$el.show();
                    } else {
                        that.options.isAuthenticated = false;
                        that.$el.attr('isAuthenticated', false);
                        that.destroy();
                    }
                });
            };

            var result = false;
            if ($.isFunction(this.options.authorizeMethod)) {
                result = this.execute(this.options.authorizeMethod, $.com.getFormData(this.$form))
            }

            if (this.options.authorizeLogic === 'and') {
                if (result && $.com.hasValue(this.options.functionid)) {
                    serverAuthorize(this.options.functionid);
                } else {
                    this.options.isAuthenticated = false;
                    this.$el.attr('isAuthenticated', false);
                    //this.destroy();
                }
            } else if (this.options.authorizeLogic === 'or') {
                if (!result) {
                    if ($.com.hasValue(this.options.functionid)) {
                        serverAuthorize(this.options.functionid);
                    } else {
                        this.options.isAuthenticated = false;
                        this.$el.attr('isAuthenticated', false);
                        //this.destroy();
                    }
                } else {
                    this.options.isAuthenticated = true;
                    this.$el.show();
                }
            }
        }
    };

    Button.prototype.onAttachmentDownload = function () {
        var $buttons = this.$el.closest('.k-upload-status');
        if ($.com.isJqueryObject($buttons)) {
            this.options.url = $buttons.attr('data-path');
            this.options.fileName = $buttons.attr('data-file-name');
            if ($.com.hasValue(this.options.url)) {
                this.onDownload();
            }
        }
    };

    Button.prototype.getForm = function () {
        //form 取 data-form 指定元素或者 第一个被标记为 data-toggle="form" 的父元素
        var $form = this.$form;
        this.$form = this.$el.attr(_config_.attribute.formAttr);
        if ($.com.hasValue(this.$form)) {
            this.$form = $(this.$form).first();
        } else {
            this.$form = this.$el.parents(_config_.selector.form).first();
        }

        if ($.com.isJqueryObject(this.$form) && $.com.isJqueryObject($form) && !this.$form.equal($form)) {
            var form = $form.data(_config_.form.namespace);
            if ($.com.hasValue(form) && $.com.isJqueryObject(form.$buttons)) {
                form.$buttons.removeItem(this.$el);
            }

            form = this.$form.data(_config_.form.namespace);
            if ($.com.hasValue(form)) {
                form.$buttons.push(this.$el[0]);
            }
        }
    };

    //plug-in
    $.fn.button = function (options) {
        var value = undefined;
        var args = Array.prototype.slice.call(arguments, 1);
        this.each(function () {
            var $this = $(this);
            var data = $this.data(_config_.button.namespace);

            if ($.com.isNullOrEmpty(data)) {
                data = new Button(this, typeof options === 'object' && options);
                $this.data(_config_.button.namespace, data);
            }

            if (typeof options === 'string') {
                //if options is not a method
                if ($.inArray(options, data.methods) < 0) {
                    throw 'Unknown method: ' + options;
                }

                //if options is a plugin method, to execute
                value = data[options].apply(data, args);
            }
        });

        return typeof value === 'undefined' ? this : value;
    };
})(jQuery);